package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.core.utils.ObjectUtils;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.HttpResult;
//import cn.edu.tju.elb.service.BusinessService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.repository.BusinessRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/businesses")
@Tag(name="管理店铺", description = "提供对店铺的增删改查功能")
public class BusinessController {
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private UserRepository userRepository;

   // @Autowired
   // BusinessService businessService;

    @GetMapping("")
    @Operation(summary = "查询所有店铺",method = "GET")
    public HttpResult<List<Business>> getBusinesses()
    {
        List<Business> businesses = businessRepository.findAll();
        return HttpResult.success(businesses);
    }

    @PostMapping("")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "新增店铺", description = "仅管理员可操作")
    public HttpResult<Business> addBusiness(@RequestBody Business business) {
        User user = userService.getUserWithAuthorities().get();
        User owner = userRepository.findById(business.getBusinessOwner().getId()).orElse(null);
        if (owner == null) {
            return HttpResult.failure(ResultCodeEnum.USER_NOT_FOUND);
        }
        Business newBusiness = new Business();
        BeanUtils.copyProperties(business, newBusiness);
        ObjectUtils.newObjectDefaultInit(newBusiness, user);
        newBusiness.setBusinessName(business.getBusinessName());
        newBusiness.setBusinessOwner(owner);
        return HttpResult.success(businessRepository.save(newBusiness));

    }

    @GetMapping("/{id}")
    @Operation(summary = "根据id查询店铺",method = "GET")
    public HttpResult<Business> getBusiness(@PathVariable("id") Long id){
        Optional<Business> businessOpt = businessRepository.findById(id);
        if (businessOpt.isEmpty()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
        }
        return HttpResult.success(businessOpt.get());


}

@PutMapping("/{id}")
@Operation(summary = "完全更新店铺",method = "PUT")
public HttpResult<Business> updateBusiness(@PathVariable("id") Long id, @RequestBody Business business) {
    try {
        // 参数校验
        if (id == null || id <= 0) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "商家ID不能为空且必须大于0");
        }

        if (business == null) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "商家信息不能为空");
        }

        if (business.getBusinessName() == null || business.getBusinessName().trim().isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "商家名称不能为空");
        }

        // 检查商家是否存在
        Optional<Business> existingBusinessOpt = businessRepository.findById(id);
        if (existingBusinessOpt.isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
        }

        Business existingBusiness = existingBusinessOpt.get();

        // 检查商家名称是否重复（排除自身）
        List<Business> sameNameBusinesses = businessRepository.findByBusinessNameAndIdNot(business.getBusinessName(), id);
        if (!sameNameBusinesses.isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.BUSINESS_EXISTS);
        }

        // 更新所有字段
        existingBusiness.setBusinessName(business.getBusinessName());
        existingBusiness.setBusinessAddress(business.getBusinessAddress());
        existingBusiness.setBusinessExplain(business.getBusinessExplain());
        existingBusiness.setBusinessImg(business.getBusinessImg());
        existingBusiness.setOrderTypeId(business.getOrderTypeId());
        existingBusiness.setStartPrice(business.getStartPrice());
        existingBusiness.setDeliveryPrice(business.getDeliveryPrice());
        existingBusiness.setRemarks(business.getRemarks());
        Business updatedBusiness = businessRepository.save(existingBusiness);
        return HttpResult.success(updatedBusiness);
    } catch (Exception e) {
        return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR);
    }

}

@PatchMapping("/{id}")
@Operation(summary = "部分更新店铺",method = "PATCH")
public HttpResult<Business> patchBusiness(@PathVariable("id") Long id, @RequestBody Map<String, Object> updates){
    try {
        // 参数校验
        if (id == null || id <= 0) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "商家ID不能为空且必须大于0");
        }

        if (updates == null || updates.isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "更新内容不能为空");
        }

        // 检查商家是否存在
        Optional<Business> existingBusinessOpt = businessRepository.findById(id);
        if (existingBusinessOpt.isEmpty()) {
            return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
        }

        Business existingBusiness = existingBusinessOpt.get();

        // 部分更新：只更新提供的字段
        for (Map.Entry<String, Object> entry : updates.entrySet()) {
            String field = entry.getKey();
            Object value = entry.getValue();

            switch (field) {
                case "businessName":
                    if (value != null) {
                        String newName = value.toString().trim();
                        if (!newName.isEmpty()) {
                            // 检查名称是否重复
                            List<Business> sameNameBusinesses = businessRepository.findByBusinessNameAndIdNot(newName, id);
                            if (!sameNameBusinesses.isEmpty()) {
                                return HttpResult.failure(ResultCodeEnum.BUSINESS_EXISTS);
                            }
                            existingBusiness.setBusinessName(newName);
                        }
                    }
                    break;
                case "businessAddress":
                    existingBusiness.setBusinessAddress(value != null ? value.toString() : null);
                    break;
                case "businessExplain":
                    existingBusiness.setBusinessExplain(value != null ? value.toString() : null);
                    break;
                case "businessImg":
                    existingBusiness.setBusinessImg(value != null ? value.toString() : null);
                    break;
                case "orderTypeId":
                    if (value != null) {
                        existingBusiness.setOrderTypeId(Integer.parseInt(value.toString()));
                    }
                    break;
                case "startPrice":
                    if (value != null) {
                        existingBusiness.setStartPrice(new BigDecimal(value.toString()));
                    }
                    break;
                case "deliveryPrice":
                    if (value != null) {
                        existingBusiness.setDeliveryPrice(new BigDecimal(value.toString()));
                    }
                    break;
                case "remarks":
                    existingBusiness.setRemarks(value != null ? value.toString() : null);
                    break;
                case "businessOwner":
                    if (value != null && value instanceof Map) {
                        Map<?, ?> ownerMap = (Map<?, ?>) value;
                        if (ownerMap.containsKey("id")) {
                            Long ownerId = Long.parseLong(ownerMap.get("id").toString());
                            Optional<User> newOwnerOpt = userRepository.findById(ownerId);
                            if (newOwnerOpt.isEmpty()) {
                                return HttpResult.failure(ResultCodeEnum.USER_NOT_FOUND);
                            }
                            existingBusiness.setBusinessOwner(newOwnerOpt.get());
                        }
                    }
                    break;
            }
        }

        Business updatedBusiness = businessRepository.save(existingBusiness);
        return HttpResult.success(updatedBusiness);

    } catch (Exception e) {
        return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR);
    }
}

@DeleteMapping("/{id}")
@Operation(summary = "删除店铺",method = "DELETE")
public HttpResult<Business> deleteBusiness(@PathVariable("id") Long id){
    try {
        // 参数校验
        if (id == null || id <= 0) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "商家ID不能为空且必须大于0");
        }

        // 检查商家是否存在
        if (!businessRepository.existsById(id)) {
            return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
        }

        // 执行删除
        businessRepository.deleteById(id);

        return HttpResult.success(null);

    } catch (Exception e) {
        return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR);
    }
}
}
